package com.zzy.demo.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzy.demo.common.util.rsa.CmsKeyPair;
import com.zzy.demo.common.util.rsa.HutoolRsaUtil;

@Controller
@RequestMapping("/rsa/hutool")
public class RsaHutoolController {

	@RequestMapping("/index")
	public String generateKey(HttpServletRequest request, ModelMap modelMap) throws Exception {
		CmsKeyPair keyPair = HutoolRsaUtil.generateKeyPair();
		String privateKey = keyPair.getPrivateKeyStr();
		String publicKey = keyPair.getPublicKeyStr();
		request.getSession().setAttribute("session_private_key", privateKey);
		request.getSession().setAttribute("session_public_key", publicKey);
		modelMap.put("private_key", privateKey);
		modelMap.put("public_key", publicKey);
		return "rsa_hutool";
	}

	@RequestMapping("/decode")
	@ResponseBody
	public String decode(HttpServletRequest request, String hexEncodeText) {
		String privateKey = (String) request.getSession().getAttribute("session_private_key");
		String text = null;
		try {
			text = HutoolRsaUtil.decryptByPrivateKey(privateKey, hexEncodeText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return text;
	}
	
	
	@RequestMapping("/encode")
	@ResponseBody
	public String encode(HttpServletRequest request, String text) throws Exception {
		String publicKey = (String) request.getSession().getAttribute("session_public_key");
    	String backEncodeStr = null;
		try {
			//后端加密
	    	backEncodeStr = HutoolRsaUtil.encryptByPublicKey(publicKey, text);
	    	System.out.println("backEncodeStr:"+backEncodeStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return backEncodeStr;
	}

}
